import paramiko
import threading
import time
import os
from conf import *

# 拿到cmd.txt文件中的命令
with open('./cmd.txt', 'r') as f:
    cmd_line = f.readlines()
cmd = []
for c in cmd_line:
    cmd.append(c)
# 定义连接与操作


def ssh2(ip, username, passwd, cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(ip, 22, username, passwd, timeout=5)       # 尝试登录SSH设备
        except Exception as e:                                      # 登录失败
            print('登录SSH设备失败 ' + str(e))
        ssh_shell = ssh.invoke_shell()
        result1 = ssh_shell.recv(1024).decode()
        print("登录成功:\n", result1)
        # 执行命令并输入到console和文本文件
        result2 = ''
        for m in cmd:
            ssh_shell.sendall(m+' \n')
            time.sleep(2)
            result2 += ssh_shell.recv(1024).decode()
        print("命令执行完毕:\n", result2)
        ssh.close()
        with open('result.txt', 'a') as f:
            for a in result2:
                f.write(a)
    except:
        print('执行%s发生错误\n' % ip)


if __name__ == '__main__':
    print("开始执行脚本")
    for key in swip:
        ip = swip[key]
        a = threading.Thread(target=ssh2, args=(ip, username, passwd, cmd))
        a.start()
